class CatCarousel extends HTMLElement {
    constructor() {
        super();

        // 创建一个影子DOM并将模板克隆内容附加到影子根
        this.attachShadow({ mode: 'open' });

        // 初始化属性
        this.currentIdx = 0;
        this.catImages = this.getAttribute('images') ? JSON.parse(this.getAttribute('images')) : [];
    }

    connectedCallback() {
        this.render();
        this.startCarousel();
    }

    render() {
        this.shadowRoot.innerHTML = `
            <style>
                .carousel { position: relative; width: 100%; margin: auto; }
                .carousel img { width: 100%; display: none; }
                .carousel img.active { display: block; }
                .controls { text-align: center; margin-top: 10px; }
                .indicator { display: inline-block; width: 10px; height: 10px; background-color: gray; border-radius: 50%; margin: 0 5px; cursor: pointer; }
                .indicator.active { background-color: black; }
            </style>
            <div class="carousel" role="region" aria-label="猫咪图片轮播">
                ${this.catImages.map(src => `<img src="${src}" alt="A cat">`).join('')}
            </div>
            <div class="controls">
                <button id="prev">❮</button>
                ${this.catImages.map((_, i) => `<span class="indicator" data-index="${i}"></span>`).join('')}
                <button id="next">❯</button>
            </div>
        `;
        
        if (this.catImages.length > 0) {
            this.showImage(this.currentIdx);
            this.setupControls();
        }
    }

    showImage(index) {
        const images = this.shadowRoot.querySelectorAll('.carousel img');
        const indicators = this.shadowRoot.querySelectorAll('.indicator');
        images.forEach((img, i) => {
            img.classList.toggle('active', i === index);
        });
        indicators.forEach((indicator, i) => {
            indicator.classList.toggle('active', i === index);
        });
    }

    setupControls() {
        this.shadowRoot.querySelector('#prev').addEventListener('click', () => this.prevImage());
        this.shadowRoot.querySelector('#next').addEventListener('click', () => this.nextImage());
        this.shadowRoot.querySelectorAll('.indicator').forEach(indicator => 
            indicator.addEventListener('click', () => {
                this.currentIdx = parseInt(indicator.getAttribute('data-index'));
                this.showImage(this.currentIdx);
            })
        );
    }

    prevImage() {
        this.currentIdx = (this.currentIdx - 1 + this.catImages.length) % this.catImages.length;
        this.showImage(this.currentIdx);
    }

    nextImage() {
        this.currentIdx = (this.currentIdx + 1) % this.catImages.length;
        this.showImage(this.currentIdx);
    }

    startCarousel() {
        if (this.catImages.length <= 1) return;

        setInterval(() => {
            this.nextImage();
        }, 3000); // 每3秒切换一次图片
    }
}

export default CatCarousel;